package com.mask.juc.v1.c_005;

import java.util.concurrent.TimeUnit;

/**
 * 程序在纸信封过程中，如果出现异常，默认情况下锁会被释放 <br>
 * 在并发处理的过程中，在处理异常时，避免出现数据不一致的情况 <br>
 *
 * @author hx
 * @date 2021/10/11 3:53 下午
 */

public class T {
    int count = 0;
    synchronized void m(){
        System.out.println(Thread.currentThread().getName()+ " start");
        while (true){
            count ++;
            System.out.println(Thread.currentThread().getName()+ " count = " + count);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (count == 5){
                int i = 10/0; //此处抛出异常，锁将被释放
                System.out.println(i);
            }
        }
    }

    public static void main(String[] args) {
        T t = new T();
        Runnable r = new Runnable() {
            @Override
            public void run() {
                t.m();
            }
        };
        new Thread(r, "t1").start();
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(r, "t2").start();
    }
}
